package com.uwo.house.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.uwo.house.beans.PayLogEntity;
import com.uwo.house.beans.response.BillResp;
import com.uwo.house.service.IAdministratorService;
import com.uwo.house.service.IAliPayService;
import com.uwo.house.service.IOrderMeasureService;
import com.uwo.house.util.AliPayConfig;
import com.uwo.house.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by dell on 2017/10/31.
 */
@Controller
@RequestMapping("/alipay")
public class AliPayController extends BaseController {
    @Autowired
    IAliPayService aliPayService;
    @Autowired
    IOrderMeasureService orderMeasureService;
    @Autowired
    IAdministratorService administratorService;

    /**
     * 生成支付宝支付页面
     *
     * @param httpRequest
     * @param httpResponse
     */
    @RequestMapping(value = "/createalipayhtmlpage", method = RequestMethod.GET)
    @ResponseBody
    public void createAliPayHtmlPage(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String orderId = httpRequest.getParameter("orderId");
        if (!StringUtil.isEmpty(orderId)) {
            PayLogEntity payLogEntity = aliPayService.getPayLogByOrderNo(orderId);
            //总价
            String total_amount = String.valueOf(payLogEntity.getPayShouldPrice());
            //订单名称，必填
            String subject = "预约量房";
            //商品描述，可空
            String body = "";

            //接入支付宝支付流程
            aliPayService.trade_computer_pay(httpRequest, httpResponse, orderId, total_amount, subject, body);
        }
    }

    /**
     * 支付，回调函数
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/alipaynotifyurl", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void aliPayNotifyUrl(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付金额
        Double paymoney =  Double.valueOf(params.get("total_amount"));

        //计算得出通知验证结果
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.CHARSET, "RSA2");
        if (verify_result) {//验证成功
            //成功支付更新交易记录表(PAY_LOG)信息
            PayLogEntity payLogEntity = aliPayService.getPayLogByOrderNo(out_trade_no);
            if ("0".equals(payLogEntity.getPayFlag())) {
                payLogEntity.setTradeNo(trade_no);//支付宝交易号
                payLogEntity.setPayPrice(new BigDecimal(paymoney));//支付金额
                payLogEntity.setPayFlag("1");//支付状态:2已支付
                payLogEntity.setPayTime(new Date());//支付时间
                payLogEntity.setPayType("1");//支付宝支付
                aliPayService.updatePayLog(payLogEntity);
                this.orderMeasureService.addOrder(out_trade_no);//添加订单信息(order_status表)
                String userId = orderMeasureService.getUserIdByOrderId(out_trade_no);//获取用户id
                this.addRecord("我的新房预约了测量", userId, "", "");
                BillResp billResp = new BillResp();
                billResp.setAmount(BigDecimal.valueOf(paymoney));
                billResp.setCreateTime(new Date());
                billResp.setIdentification("1");
                billResp.setType("1");
                billResp.setOrderId(out_trade_no);
                billResp.setPayType("1");
                administratorService.addBillLog(billResp);//添加账目信息
                System.out.println("success");    //请不要修改或删除
            }
        } else {//验证失败
            System.out.println("fail");
        }
    }
}
